package com.example.petstore.controller;

import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.Category;
import com.example.petstore.domain.Item;
import com.example.petstore.domain.Product;
import com.example.petstore.service.CategoryService;
import com.example.petstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Controller
@SessionAttributes({"loginAdmin"})
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductService productService;

    @GetMapping("/admin/getCategoryListByKeyForJS")
    @ResponseBody
    public CommonResponse getCategoryListByKeyForJS(String keyword){
        System.out.println("keyword="+keyword);
        return categoryService.getCategoryListByKey(keyword);

    }
    @GetMapping("/admin/deleteCategoryById")
    @ResponseBody
    public CommonResponse deleteCategoryById(String categoryId){
        List<Product> productList = productService.getProductListByCategory(categoryId).getData();
        if (!productList.isEmpty()) {
            return CommonResponse.creatForError("请先删除对应的商品！");
        }else {
            return categoryService.deleteCategoryById(categoryId);
        }


    }
    @ResponseBody
    @PostMapping("/categoryEditor")/*test ok*/
    public CommonResponse itemEditor(@RequestParam("pic") MultipartFile pic,@RequestParam("categoyrId") String categoryId){
//        try{
            String descn = productService.handleFileUpload(pic,categoryId.toLowerCase());
        System.out.println(222);
            if(descn != null) {
                Category category = new Category();
                category.setMainimg(descn);
                return categoryService.updateCategoryByCategoryId(categoryId,category);
            } else  {
                return CommonResponse.creatForSuccess("您未修改");
            }
//        } catch(Exception e){
//            System.out.println(111);
//            return CommonResponse.creatForSuccess("您未修改");
//        }

    }
}
